<template>
  <div class="application-request-container">
    <div class="page-header">
      <h2>入党申请书管理</h2>
      <p>管理用户提交的入党申请书</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="申请人">
            <el-input v-model="searchForm.name" placeholder="请输入申请人姓名" clearable @clear="handleInputClear('name')"
              @input="debounceSearch" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%"
              @change="handleStatusChange">
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchApplications">
              <el-icon>
                <Search />
              </el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon>
                <Refresh />
              </el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 当前筛选条件展示 -->
      <div class="current-filters" v-if="hasActiveFilters">
        <span class="filter-label">当前筛选条件:</span>
        <el-tag v-if="searchForm.name" closable @close="clearFilter('name')" class="filter-tag">
          申请人: {{ searchForm.name }}
        </el-tag>
        <el-tag v-if="searchForm.status" closable @close="clearFilter('status')" class="filter-tag">
          状态: {{ getStatusText(searchForm.status) }}
        </el-tag>
        <el-button type="text" @click="resetSearch" class="clear-all-btn">清除所有筛选</el-button>
      </div>
    </el-card>

    <!-- 申请列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="applicationList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="申请人" min-width="100" />
        <el-table-column prop="submitTime" label="提交时间" min-width="170" :formatter="formatDateTime" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" min-width="170" :formatter="formatDateTime" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon> 查看
              </el-button>
              <el-button size="small" type="success" plain @click="handleApprove(scope.row)"
                v-if="scope.row.status === 'pending'">
                <el-icon>
                  <Check />
                </el-icon> 通过
              </el-button>
              <el-button size="small" type="danger" plain @click="handleReject(scope.row)"
                v-if="scope.row.status === 'pending'">
                <el-icon>
                  <Close />
                </el-icon> 拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看申请详情对话框 -->
    <el-dialog v-model="dialogVisible" title="申请详情" width="800px" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人" :width="140">{{ currentApplication.name }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ formatDateTime(null, null, currentApplication.submitTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="状态" :width="140">
          <el-tag :type="getStatusTagType(currentApplication.status)">
            {{ getStatusText(currentApplication.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核时间" v-if="currentApplication.reviewTime">
          {{ formatDateTime(null, null, currentApplication.reviewTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="审核时间" v-else>
          -
        </el-descriptions-item>
        <el-descriptions-item label="申请人基本情况" :span="2">
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="性别">{{ currentApplication.gender || '-' }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ currentApplication.birthDate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="民族">{{ currentApplication.nation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学历">{{ currentApplication.education || '-' }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ currentApplication.workplace || '-' }}</el-descriptions-item>
            <el-descriptions-item label="电话号码">{{ currentApplication.phoneNum || '-' }}</el-descriptions-item>
            <el-descriptions-item label="申请日期">{{ currentApplication.applyDate || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-descriptions-item>
        <el-descriptions-item label="申请书原件" :span="2">
          <div class="application-files">
            <template v-if="applicationImages.length > 0">
              <div v-for="(fileUrl, index) in applicationImages" :key="index" class="file-item">
                <el-button type="primary" link @click="handleDownload(fileUrl)" class="download-button">
                  <el-icon>
                    <Document />
                  </el-icon>
                  下载申请书原件 ({{ index + 1 }})
                </el-button>
              </div>
            </template>
            <div v-else class="no-file">
              <el-icon>
                <Document />
              </el-icon>
              <div>暂无申请书原件</div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentApplication.content" label="申请书内容" :span="2">
          <div class="application-content">
            {{ currentApplication.content }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="审核意见" :span="2">
          <div class="review-comment" v-if="currentApplication.status !== 'pending' && currentApplication.comment">
            {{ currentApplication.comment }}
          </div>
          <div class="review-comment no-content" v-else-if="currentApplication.status !== 'pending'">
            暂无审核意见
          </div>
          <div class="review-comment pending" v-else>
            <el-icon>
              <InfoFilled />
            </el-icon> 待审核
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="success" @click="handleApprove(currentApplication)"
            v-if="currentApplication.status === 'pending'">通过</el-button>
          <el-button type="danger" @click="handleReject(currentApplication)"
            v-if="currentApplication.status === 'pending'">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="reviewDialogVisible" :title="reviewType === 'approve' ? '通过申请' : '拒绝申请'" width="500px"
      :close-on-click-modal="false">
      <el-form :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核意见" prop="comment">
          <el-input v-model="reviewForm.comment" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button :type="reviewType === 'approve' ? 'success' : 'danger'" @click="submitReview"
            :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Check, Close, Document, InfoFilled
} from '@element-plus/icons-vue';
import { getApplicationList, getApplicationCount, reviewApplication } from '@/api/partyApplication';
import { useStore } from 'vuex';

const store = useStore();

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const applicationList = ref([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
});

// 详情对话框
const dialogVisible = ref(false);
const currentApplication = ref({});

// 申请书图片数组计算属性
const applicationImages = computed(() => {
  if (!currentApplication.value.handwrittenDoc) return [];

  // 按逗号分隔字符串，并过滤掉空项
  return currentApplication.value.handwrittenDoc.split(',')
    .map(url => url.trim())
    .filter(url => url);
});

// 审核对话框
const reviewDialogVisible = ref(false);
const reviewType = ref(''); // 'approve' 或 'reject'
const reviewFormRef = ref(null);
const reviewForm = reactive({
  id: '',
  comment: ''
});
const submitting = ref(false);

// 初始化加载数据
onMounted(() => {
  fetchApplications();
});

// 获取申请列表
const fetchApplications = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const queryData = {
      name: searchForm.name
    };

    // 添加状态筛选
    if (searchForm.status) {
      // 将字符串状态转换为整数
      const statusMap = {
        'pending': 0,
        'approved': 1,
        'rejected': 2
      };
      queryData.status = statusMap[searchForm.status];
    }

    // 1. 获取总数
    const countResponse = await getApplicationCount(queryData);
    console.log(countResponse.data);
    if (countResponse.data.code === 200) {
      total.value = countResponse.data.data.count || 0;
    } else {
      ElMessage.error(countResponse.data.msg || '获取申请书总数失败');
      loading.value = false;
      return;
    }

    // 2. 获取分页列表
    const response = await getApplicationList(queryData, currentPage.value, pageSize.value);

    if (response.data.code === 200) {
      const records = response.data.data.page.records || [];
      applicationList.value = records.map(item => {
        // 将整数状态转换为字符串状态
        let statusString = 'pending';
        if (item.status === 1) {
          statusString = 'approved';
        } else if (item.status === 2) {
          statusString = 'rejected';
        }

        return {
          id: item.id,
          name: item.name,
          submitTime: item.createTime,
          status: statusString,
          reviewTime: item.reviewTime || '',
          content: item.selfIntro || '',
          comment: item.review || '',
          handwrittenDoc: item.handwrittenDoc || '',
          gender: item.gender || '',
          birthDate: item.birthdate || '',
          nation: item.ethnicity || '',
          education: item.eduLevel || '',
          workplace: item.department || '',
          position: item.position || '',
          phoneNum: item.phoneNum || '',
          applyDate: item.applyDate || ''
        };
      });
      console.log('申请书列表数据:', applicationList.value);
    } else {
      ElMessage.error(response.data.msg || '获取申请书列表失败');
    }
  } catch (error) {
    console.error('获取申请列表失败:', error);
    ElMessage.error('获取申请列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索申请
const searchApplications = () => {
  currentPage.value = 1;
  fetchApplications();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchApplications();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchApplications();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchApplications();
};

// 处理输入框清除
const handleInputClear = (key) => {
  searchForm[key] = '';
  fetchApplications();
};

// 处理状态变化
const handleStatusChange = () => {
  fetchApplications();
};

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning';
    case 'approved':
      return 'success';
    case 'rejected':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待审核';
    case 'approved':
      return '已通过';
    case 'rejected':
      return '已拒绝';
    default:
      return '未知';
  }
};

// 查看申请详情
const handleView = (row) => {
  currentApplication.value = { ...row };

  // 检查并确保handwrittenDoc字段存在
  if (!currentApplication.value.handwrittenDoc) {
    currentApplication.value.handwrittenDoc = '';
  }

  dialogVisible.value = true;
};

// 处理通过申请
const handleApprove = (row) => {
  currentApplication.value = { ...row };
  reviewType.value = 'approve';
  reviewForm.id = row.id;
  reviewForm.comment = '';
  reviewDialogVisible.value = true;
};

// 处理拒绝申请
const handleReject = (row) => {
  currentApplication.value = { ...row };
  reviewType.value = 'reject';
  reviewForm.id = row.id;
  reviewForm.comment = '';
  reviewDialogVisible.value = true;
};

// 提交审核
const submitReview = async () => {
  submitting.value = true;
  try {
    // 构建审核数据，将字符串状态转换为整数
    const statusMap = {
      'pending': 0,
      'approved': 1,
      'rejected': 2
    };

    // 获取当前时间，格式化为符合Java LocalDateTime要求的格式 (yyyy-MM-dd HH:mm:ss)
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    console.log(currentTime);

    const reviewData = {
      id: reviewForm.id,
      status: statusMap[reviewType.value === 'approve' ? 'approved' : 'rejected'],
      review: reviewForm.comment,
      reviewTime: currentTime // 使用后端定义的字段名 'reviewTime'
    };

    // 调用审核API
    const response = await reviewApplication(reviewData);

    if (response.data.code === 200) {
      ElMessage.success(reviewType.value === 'approve' ? '已通过申请' : '已拒绝申请');

      // 更新本地数据
      const index = applicationList.value.findIndex(item => item.id === reviewForm.id);
      if (index !== -1) {
        applicationList.value[index].status = reviewType.value === 'approve' ? 'approved' : 'rejected';
        applicationList.value[index].reviewTime = currentTime; // 使用相同的时间更新前端显示
        applicationList.value[index].comment = reviewForm.comment;
      }

      // 关闭对话框
      reviewDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.msg || '审核操作失败');
    }
  } catch (error) {
    console.error('提交审核失败:', error);
    ElMessage.error('提交审核失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 即时搜索
const debounceSearch = () => {
  fetchApplications();
};

// 添加当前筛选条件展示
const hasActiveFilters = computed(() => {
  return searchForm.name !== '' || searchForm.status !== '';
});

const clearFilter = (key) => {
  searchForm[key] = '';
  fetchApplications();
};

// 处理文件下载
const handleDownload = (fileUrl) => {
  console.log(fileUrl);
  // 创建一个临时的 a 标签用于下载
  const link = document.createElement('a');
  link.href = fileUrl;
  // 从 URL 中提取文件名，如果没有则使用默认名称
  const fileName = fileUrl.split('/').pop() || '申请书原件';
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.application-request-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.application-content {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
  color: #606266;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
}

.application-files {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.file-item {
  display: flex;
  align-items: center;
}

.download-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.download-button .el-icon {
  margin-right: 4px;
}

.no-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  height: 100px;
  width: 100%;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.no-file .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.current-filters {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-label {
  font-weight: bold;
  color: #606266;
}

.filter-tag {
  margin-right: 10px;
}

.clear-all-btn {
  margin-top: 10px;
  margin-left: auto;
}
</style>